package com.sinoglobal.ningxia.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Movie;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout.LayoutParams;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.orhanobut.logger.Logger;
import com.readystatesoftware.systembartint.SystemBarTintManager;
import com.sinoglobal.dumping.base.Dumpling_SharedPreferenceUtil;
import com.sinoglobal.ningxia.R;
import com.sinoglobal.ningxia.beans.VersionVo;
import com.sinoglobal.ningxia.downdata.imp.RemoteImpl;
import com.sinoglobal.ningxia.fragment.LeftFragment;
import com.sinoglobal.ningxia.frame.BaseSlidingFragmentActivity;
import com.sinoglobal.ningxia.frame.FlyApplication;
import com.sinoglobal.ningxia.frame.IChangeFragment;
import com.sinoglobal.ningxia.frame.SlidingMenu;
import com.sinoglobal.ningxia.http.Code;
import com.sinoglobal.ningxia.qr.CaptureActivity;
import com.sinoglobal.ningxia.service.PushService;
import com.sinoglobal.ningxia.utils.EquipmentUtil;
import com.sinoglobal.ningxia.utils.FlyUtil;
import com.sinoglobal.ningxia.utils.SharedPreferenceUtil;
import com.sinoglobal.ningxia.utils.StringUtil;
import com.sinoglobal.ningxia.utils.UserUtils;
import com.sinoglobal.ningxia.version.VersionUitls;
import com.sinoglobal.ningxia.version.VersionUpgradeActivity;
import com.sinoglobal.ningxia.widget.MyRelativeLayout;
import com.sinoglobal.ningxia.widget.anigif.GifMovieView;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionNo;
import com.yanzhenjie.permission.PermissionYes;

import java.lang.reflect.Field;
import java.util.List;

@SuppressWarnings("ResourceType")
public class MainActivity extends BaseSlidingFragmentActivity implements IChangeFragment, OnClickListener {

    public static SlidingMenu mSlidingMenu;
    private LeftFragment mLeftFragment;// 左侧栏
    // private int currentLabel = 0; // 当前位置
    private Activity mActivity;
    private ImageView topLeft;// 返回键
    private ImageView topRight;// 二维码扫描
    private long TimeInterval;// 时间间隔，记录back键两次点击事件间隔
    private MyRelativeLayout relaMain;// 主页面layout
    private String ANIMATION = "animation";
    private static boolean checkVersion = true;// 当用户打开应用弹出更新版本信息时
    private MyBroadcastReceiver receiver;
    private int top;//状态栏高度
    private RelativeLayout rlTopTitle;//title布局

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        FlyUtil.addAppActivity(this);
        getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        /*
         * if (savedInstanceState != null) { currentLabel =
		 * savedInstanceState.getInt("currentLabel", 0); }
		 */
        mActivity = this;
        setContentView(R.layout.activity_main);
        top = getTitleTop();

        initSlidingMenu();
        init();
        initState();
        bootAnimation();
        if (AndPermission.hasPermission(this, Manifest.permission.READ_PHONE_STATE, Manifest.permission.READ_EXTERNAL_STORAGE)) {
            //需要权限READ_PHONE_STATE
            startService(new Intent(MainActivity.this, PushService.class));
            if (EquipmentUtil.checkNetState(this) && checkVersion) {
                getVersiont();
            }
        } else {
            AndPermission.with(this)
                    .requestCode(1001)
                    .permission(Manifest.permission.READ_PHONE_STATE, Manifest.permission.READ_EXTERNAL_STORAGE)
                    .send();
        }

        IntentFilter intentFilter = new IntentFilter("com.sino.share");
        receiver = new MyBroadcastReceiver();
        registerReceiver(receiver, intentFilter);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        // 只需要调用这一句，第一个参数是当前Acitivity/Fragment，回调方法写在当前Activity/Framgent。
        AndPermission.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    // 成功回调的方法，用注解即可，里面的数字是请求时的requestCode。
    @PermissionYes(1001)
    private void getLocationYes(List<String> grantedPermissions) {
        if (EquipmentUtil.checkNetState(this) && checkVersion) {
            getVersiont();
        }
        // TODO 申请权限成功。
        EquipmentUtil.getInstance(FlyApplication.context).getTerminalPID();
        //需要权限READ_PHONE_STATE
        startService(new Intent(MainActivity.this, PushService.class));
    }

    // 失败回调的方法，用注解即可，里面的数字是请求时的requestCode。
    @PermissionNo(1001)
    private void getLocationNo(List<String> deniedPermissions) {
        // 用户否勾选了不再提示并且拒绝了权限，那么提示用户到设置中授权。
        if (AndPermission.hasAlwaysDeniedPermission(this, deniedPermissions)) {
            // 第一种：用默认的提示语。
            AndPermission.defaultSettingDialog(this, 1001).show();
        }
    }

    // 成功回调的方法，用注解即可，里面的数字是请求时的requestCode。
    @PermissionYes(1005)
    private void getCaptureYes(List<String> grantedPermissions) {
        // TODO 申请权限成功。
        toCaptureActivity();
    }

    // 失败回调的方法，用注解即可，里面的数字是请求时的requestCode。
    @PermissionNo(1005)
    private void getCaptureNo(List<String> deniedPermissions) {
        // 用户否勾选了不再提示并且拒绝了权限，那么提示用户到设置中授权。
        if (AndPermission.hasAlwaysDeniedPermission(this, deniedPermissions)) {
            // 第一种：用默认的提示语。
            AndPermission.defaultSettingDialog(this, 1005).show();
        }
    }

    public class MyBroadcastReceiver extends BroadcastReceiver {

        // action 名称
        public void onReceive(Context context, Intent intent) {

            if (intent.getAction().equals("com.sino.share")) {
//                Toast.makeText(FlyApplication.context, "dddd", Toast.LENGTH_LONG).show();

            }

        }

    }

    @SuppressLint("NewApi")
    private void init() {
        topLeft = (ImageView) findViewById(R.id.btn_sliding);
        topLeft.setOnClickListener(this);
        topRight = (ImageView) findViewById(R.id.img_right);
        topRight.setOnClickListener(this);
        rlTopTitle = (RelativeLayout) findViewById(R.id.rela1);

    }

    // 开机动画
    private void bootAnimation() {
        // 如果运行过开机动画 直接停止执行下边代码
        if (SharedPreferenceUtil.getBoolean(mActivity, ANIMATION))
            return;
        relaMain = (MyRelativeLayout) findViewById(R.id.main_layout);
        final RelativeLayout rela = (RelativeLayout) findViewById(R.id.main_layout);
        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
        lp.addRule(RelativeLayout.CENTER_IN_PARENT);
        final GifMovieView view = new GifMovieView(this);
        view.setMovieResource(R.drawable.gold_animation);
        view.setLayoutParams(lp);
        rela.addView(view);
        Animation animation = AnimationUtils.loadAnimation(this, R.anim.gold_animation);
        view.startAnimation(animation);
        animation.setAnimationListener(new AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
                relaMain.setIntercept(true);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                rela.removeView(view);
                relaMain.setIntercept(false);
                SharedPreferenceUtil.saveBoolean(mActivity, ANIMATION, true);
            }
        });

    }

    @Override
    protected void onStop() {
        super.onStop();
//		mSlidingMenu.showContent();

    }

    /**
     * @author qiwx
     * @createdate 2014-10-13 下午5:23:31
     * @description
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        boolean isAutoChecked = SharedPreferenceUtil.getBoolean(FlyApplication.context, "autoLogin");//自动登录
        if ("".equalsIgnoreCase(FlyApplication.userId)) {//未登录
            if (!isAutoChecked) {//不自动登录清楚密码
                Logger.i("清空SP");
                SharedPreferenceUtil.saveString(FlyApplication.context, "autoPwd", "");//密码
                UserUtils.ExitSccess();
                Dumpling_SharedPreferenceUtil.clear(mActivity);
            }
        }
        unregisterReceiver(receiver);
        FlyUtil.removeAppActivity(this);
    }

    private void initSlidingMenu() {
        int mScreenWidth = FlyApplication.widthPixels;
        // setBehindContentView(R.layout.main_left_layout);// 设置左菜单
        // customize the SlidingMenu
        mSlidingMenu = getSlidingMenu();
        mSlidingMenu.setMode(SlidingMenu.LEFT);// 设置是左滑
        setBehindContentView(R.layout.main_left_layout);
        mSlidingMenu.setShadowWidth(mScreenWidth / 40);// 设置阴影宽度
        mSlidingMenu.setBehindOffset(mScreenWidth / 4);// 设置菜单宽度
        mSlidingMenu.setFadeDegree(0.35f);// 设置淡入淡出的比例
        mSlidingMenu.setShadowDrawable(R.drawable.slidingmenu_shadow);// 设置左菜单阴影图片
        mSlidingMenu.setSecondaryShadowDrawable(R.drawable.right_shadow);// 设置右菜单阴影图片
        mSlidingMenu.setFadeEnabled(true);// 设置滑动时菜单的是否淡入淡出
        mSlidingMenu.setBehindScrollScale(0.333f);// 设置滑动时拖拽效果
        mSlidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);

		/*
         * mSlidingMenu.setOnOpenListener(new OnOpenListener() {
		 * 
		 * @Override public void onOpen() { if (currentLabel == 1) {
		 * InputMethodManager imm = (InputMethodManager)
		 * getSystemService(Context.INPUT_METHOD_SERVICE);
		 * System.out.println(imm.isActive()); if (getCurrentFocus() != null) {
		 * imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
		 * InputMethodManager.HIDE_NOT_ALWAYS); } } // 关闭输入法
		 * 
		 * } });
		 */
        FragmentTransaction mFragementTransaction = getSupportFragmentManager().beginTransaction();
        Fragment f = new HomeFragment();
        mFragementTransaction.replace(R.id.centerLayout, f);
        if (null == mLeftFragment) {
            mLeftFragment = new LeftFragment();
        }
        mLeftFragment.setChangeFragmentListener(this);
        mFragementTransaction.replace(R.id.main_left_fragment, mLeftFragment);

        mFragementTransaction.commit();
    }


    @Override
    public void changeFragment(int id) {
        switch (id) {
            case 0:
                Log.i("dd", id + "---");
                break;
            case 1:
                Log.i("dd", id + "---");
                break;
            case 2:
                Log.i("dd", id + "---");
                break;
            case 3:
                break;
            case 4:
                Log.i("dd", id + "---");
                break;
            case 5:
                Log.i("dd", id + "---");
                break;

        }
    }

    /**
     * @return
     * @throws Exception
     * @author qiwx
     * @createdate 2014-6-10 下午2:17:40
     * @Description:检测版本信息
     * @type
     */
    private void getVersiont() {
        new AsyncTask<Void, Void, VersionVo>() {
            @Override
            protected void onPostExecute(VersionVo result) {
                // Auto-generated method stub
                super.onPostExecute(result);
                if (result == null) {
                    return;
                }
                if (Code.CODE_SUCCESS != result.getCode()) {
                    return;
                }
                Logger.i("更新:" + result.getUrl());
                if (!StringUtil.equals(String.valueOf(result.getNew_banben()), VersionUitls.getVersionName(FlyApplication.context))) {
                    showDialog(result);// 新版本号大于当前版本号时，弹出更新对话框
                }
            }

            @Override
            protected void onPreExecute() {
                // Auto-generated method stub
                super.onPreExecute();

            }

            @Override
            protected VersionVo doInBackground(Void... params) {
                try {
                    return RemoteImpl.getInstance().getVersionInfo();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return null;
            }
        }.execute();

    }

    /**
     * @param result
     * @author czz
     * @updatedate 2014-3-24 上午11:15:26
     * @Description: (显示升级的dialog, 如需要自定义dialog，可自己定义)
     */
    private void showDialog(final VersionVo result) {
        AlertDialog.Builder builder = new Builder(MainActivity.this);
        builder.setIcon(R.drawable.ic_launcher);
        builder.setTitle(getString(R.string.update_to) + result.getNew_banben());
        builder.setMessage(result.getGengxin());
        builder.setCancelable(false);
        builder.setNegativeButton(getString(R.string.update), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (!result.getUrl().contains(".apk")) {
                    showShortToastMessage(getString(R.string.addr_error));
                    return;

                }
                Intent intent = new Intent(MainActivity.this, VersionUpgradeActivity.class);
                intent.putExtra(VersionUpgradeActivity.DOWNLOAD, result.getUrl());
                FlyUtil.intentForward(MainActivity.this, intent);
            }
        });
        builder.setPositiveButton(getString(R.string.btn_cancle), new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                checkVersion = false;
            }
        });
        builder.show();
    }

    protected void showShortToastMessage(String string) {
        // Auto-generated method stub
        Toast.makeText(FlyApplication.context, string, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            // 侧滑按钮
            case R.id.btn_sliding:
                mSlidingMenu.showMenu();
                break;
            case R.id.img_right:
                if (AndPermission.hasPermission(MainActivity.this, Manifest.permission.RECORD_AUDIO, Manifest.permission.CAMERA)) {
                    //有相机权限
                    toCaptureActivity();
                } else {
                    AndPermission.with(MainActivity.this)
                            .requestCode(1005)
                            .permission(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA)
                            .send();
                }
                break;

        }

    }

    private void toCaptureActivity() {
        FlyUtil.intentForward(mActivity, CaptureActivity.class);
    }

    // 按下物理返回键
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((System.currentTimeMillis() - TimeInterval) > 2000) {
                Toast.makeText(FlyApplication.context, R.string.ExitInfo, Toast.LENGTH_SHORT).show();
                TimeInterval = System.currentTimeMillis();

            } else {
                FlyApplication.isGpsFlag = true;
                FlyApplication.isGpsFlag1 = true;
                FlyApplication.isInActivityFlag = 0;
                FlyApplication.isInActivityFlag1 = 0;
                try {
                    FlyUtil.exitApp();
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
            return true;
        }
        return super.onKeyDown(keyCode, event);

    }

    class CustomGifView extends View {
        Movie mMovie;
        private long mMovieStart;

        public CustomGifView(Context context) {
            super(context);
            mMovie = Movie.decodeStream(getResources().openRawResource(R.drawable.gold_animation));
        }

        public void onDraw(Canvas canvas) {
            long now = android.os.SystemClock.uptimeMillis();

            if (mMovieStart == 0) { // first time
                mMovieStart = now;
            }
            if (mMovie != null) {

                int dur = mMovie.duration();
                if (dur == 0) {
                    dur = 1000;
                }
                int relTime = (int) ((now - mMovieStart) % dur);
                mMovie.setTime(relTime);
                mMovie.draw(canvas, 0, 0);
                invalidate();
            }
        }
    }

    //关闭左侧侧拉蓝
    public void CloseLeftMenu() {
        if (mSlidingMenu != null && mSlidingMenu.isMenuShowing()) {
            mSlidingMenu.toggle();

        }
    }

    /**
     * 开启沉浸式状态栏
     * 需要在xml里的跟布局添加  android:clipToPadding="false"  android:fitsSystemWindows="true"
     */
    public void openChenJInShi() {
        // 4.4及以上版本开启
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            setTranslucentStatus(true);
        }

        SystemBarTintManager tintManager = new SystemBarTintManager(this);
        tintManager.setStatusBarTintEnabled(true);
        tintManager.setNavigationBarTintEnabled(false);

        // 自定义颜色
        tintManager.setTintColor(Color.parseColor("#dd191d"));
    }

    @TargetApi(19)
    private void setTranslucentStatus(boolean on) {
        Window win = getWindow();
        WindowManager.LayoutParams winParams = win.getAttributes();
        final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
        if (on) {
            winParams.flags |= bits;
        } else {
            winParams.flags &= ~bits;
        }
        win.setAttributes(winParams);
    }

    /**
     * 沉浸式状态栏
     */
    private void initState() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            //透明状态栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            RelativeLayout linear_bar = (RelativeLayout) findViewById(R.id.ll_bar);
            linear_bar.setVisibility(View.VISIBLE);
            //动态的设置隐藏布局的高度
            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) linear_bar.getLayoutParams();
            Logger.e("状态栏高度:" + top);
            params.height = top;
            linear_bar.setLayoutParams(params);
        }

    }

    private int getTitleTop() {
        Class<?> c = null;
        Object obj = null;
        Field field = null;
        int x = 0, sbar = 0;
        try {
            c = Class.forName("com.android.internal.R$dimen");
            obj = c.newInstance();
            field = c.getField("status_bar_height");
            x = Integer.parseInt(field.get(obj).toString());
            sbar = getResources().getDimensionPixelSize(x);// 状态栏高度
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        Log.e("状态栏高度:", sbar + ":" + x);
        return sbar;
    }
}
